cc.Class({
    extends: cc.Component,

    properties: {
        target: {
            default: null,
            type: cc.Node
        },
        dir:0
    },

    // use this for initialization
    onLoad: function () {
        this.camera = this.getComponent(cc.Camera);
        this.rotationFlag = false;
    },

    onEnable: function () {
        cc.director.getPhysicsManager().attachDebugDrawToCamera(this.camera);
    },
    onDisable: function () {
        cc.director.getPhysicsManager().detachDebugDrawFromCamera(this.camera);
    },


    // called every frame, uncomment this function to activate update callback
    lateUpdate: function (dt) {
        let targetPos = this.target.convertToWorldSpaceAR(cc.v2(0,0));
        let nodeRotation = this.node.rotation;
        let targerDir = parseInt(Math.abs((360 + this.target.rotation + this.dir) % 360) / 45);
        this.node.position = this.node.parent.convertToNodeSpaceAR(targetPos);
        if(this.target.getComponent('role').body.angularVelocity == 0){
            let finished = cc.callFunc(function() {
                this.rotationFlag = false;
            }, this);
            if((nodeRotation - this.dir)%360 != 0 && (targerDir == 0 || targerDir == 7) && this.rotationFlag == false){
                this.rotationFlag = true;
                this.node.runAction(cc.sequence(cc.rotateTo(1,this.dir),finished));
            }
            if((nodeRotation - this.dir)%360 == 0 && (targerDir == 3 || targerDir == 4) && this.rotationFlag == false){
                this.rotationFlag = true;
                this.node.runAction(cc.sequence(cc.rotateTo(1,this.dir + 180),finished));
            }
        }   
    },
});